#include <webx/route.h>

class GetFileMenuList : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(GetFileMenuList)

int GetFileMenuList::process()
{
	param_string(path);

	int res = 0;
	vector<string> vec;
	string urlpath = "/dat/pub/" + path;
	string filepath = app->getPath() + urlpath.substr(1);

	webx::CheckFilePath(path, 0);

	if (path.length() > 0)
	{
		filepath += "/";
		urlpath += "/";
	}

	urlpath = stdx::replace(urlpath, "\\", "/");
	urlpath = stdx::replace(urlpath, "//", "/");

	stdx::GetFolderContent(vec, filepath, ePATH);

	auto sortfunc = [](const string& a, const string& b){
		int m = stdx::atoi(a.c_str());
		int n = stdx::atoi(b.c_str());
		
		if (m == n) return a < b;
		
		return m < n;
	};
	
	std::sort(vec.begin(), vec.end(), sortfunc);

	JsonElement arr = json.addArray("list");

	for (auto& item : vec)
	{
		vector<string> tmp;
		const string path = filepath + item;
	
		stdx::GetFolderContent(tmp, path, eFILE);
		
		std::sort(tmp.begin(), tmp.end(), sortfunc);

		for (auto& name : tmp)
		{
			auto pos = name.rfind('.');
			JsonElement data = arr[res++];
	
			data["folder"] = item;
			data["icon"] = webx::GetFileIcon(name);
			data["url"] = stdx::EncodeURL(urlpath + item + "/" + name);
			data["datetime"] = DateTime(path::mtime(path + "/" + name)).toString();

			if (pos == string::npos)
			{
				data["title"] = name;
			}
			else
			{
				data["title"] = name.substr(0, pos);
			}
		}
	}

	json["code"] = res;
	out << json;

	return XG_OK;
}